package com.fm.magic.net.baidu;

import com.fm.base.json.JsonArray;
import com.fm.base.json.JsonObject;
import com.fm.base.net.proxy.HttpProxy;
import com.fm.commons.net.http.HttpClient;
import com.fm.commons.net.http.HttpRequest;
import com.fm.commons.net.http.HttpResponse;
import com.fm.commons.net.http.converter.JsonObjectConverter;
import com.fm.commons.net.http.converter.JsoupConverter;
import com.fm.commons.net.http.entity.FormDataProvider;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Translator {
	public static class Result {
		public String src;
		public String dst;

		private Result(String src, String dst) {
			this.src = src;
			this.dst = dst;
		}

		@Override
		public String toString() {
			return src + " -> " + dst;
		}
	}

	public static Result translateEN2CN(String word) {
		return translateEN2CN(word, null);
	}

	public static Result translateEN2CN(String word, HttpProxy proxy) {
		try (HttpClient client = new HttpClient()) {
			//用于md5加密
			int salt = new Random().nextInt(10000);

			// 对appId+源文+随机数+token计算md5值
			String md5 = DigestUtils.md5Hex("2015063000000001" + word + salt + "12345678");

			//使用Post方式，组装参数
			List<NameValuePair> nvps = new ArrayList<>();
			nvps.add(new BasicNameValuePair("q", word));
			nvps.add(new BasicNameValuePair("from", "en"));
			nvps.add(new BasicNameValuePair("to", "zh"));
			nvps.add(new BasicNameValuePair("appid", "2015063000000001"));
			nvps.add(new BasicNameValuePair("salt", String.valueOf(salt)));
			nvps.add(new BasicNameValuePair("sign", md5));


			//创建httpclient链接，并执行
			HttpRequest request = HttpRequest
                .post(URI.create("http://api.fanyi.baidu.com/api/trans/vip/translate"), new FormDataProvider(nvps))
				.setProxy(proxy).build();
			HttpResponse response = client.send(request);
			if (response.getStatusCode() == 200) {
				JsonObject jsonObject = response.convert(JsonObjectConverter.Instance);
				JsonArray array = jsonObject.getJsonArray("trans_result");
				if (array != null && !array.isEmpty()) {
					return new Result(array.getJsonObject(0).getString("src"), array.getJsonObject(0).getString("dst"));
				} else {
					return null;
				}
			} else {
				throw new RuntimeException(response.getStatusCode() + ":" + response.convert(JsoupConverter.Instance));
			}
		}
	}
}
